package top.infopub.mgr.cap.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.mkt.FinancialInstitutionsDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.dao.FinancialInstitutionsDao;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.FinancialInstitutionsService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.model.cap.FinancialInstitutions;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.UtilTools;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Warking
 * @Date 2021/5/23 21:24
 * @Version 1.0  金融机构
 */
@Controller
@RequestMapping("/financialInstitutions")
public class FinancialInstitutionsController {
    @Autowired
    private FinancialInstitutionsService financialInstitutionsService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CapProcessManageService capProcessManageService;
    @Autowired
    private FinancialInstitutionsDao financialInstitutionsDao;

    /*金融机构选择列表接口*/
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<FinancialInstitutions> queryDataByCondition(FinancialInstitutions financialInstitutions, ParamPage paramPage) throws ParseException {
        Page<FinancialInstitutions> page = new Page();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //处理时间范围
        if (!StringUtils.isEmpty(financialInstitutions.getDates())) {
            String[] splitTime = financialInstitutions.getDates().split("~");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            financialInstitutions.setStartDate(format.parse(splitTime[0]));
            financialInstitutions.setEndDate(format.parse(splitTime[1]));
        }
        page = financialInstitutionsService.selectPage(page, financialInstitutions);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }


    /**
     * 金融机构选择的详情跳转
     *
     * @return
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("proCode", proCode);
        request.setAttribute("id", id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        FinancialInstitutions financialInstitutions = financialInstitutionsService.selectByKey(id);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        if (financialInstitutions != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), financialInstitutions.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), financialInstitutions.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(financialInstitutions.getProcessId()) && financialInstitutions.getProcessId().length() > 10) {
                request.setAttribute("processId", financialInstitutions.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(financialInstitutions.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), financialInstitutions.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return "cap/lay-ApprovalAgency-detail";
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        capProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    //金融机构选择详情页面 ID 是主表的SGUID
    @RequestMapping("/queryByIdDetail")
    @ResponseBody
    public FinancialInstitutionsDto queryDetailById(String proCode, String id) {
        FinancialInstitutionsDto dto = financialInstitutionsService.queryDetailById(id, proCode);
        return dto;
    }

    //金融机构选择 保存提交 前端传一个融资的数据过来
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String financialInstitutionsDto, String identifying, String proCode, String id) {
        if (StringUtils.isEmpty(financialInstitutionsDto)) {
            return RspVo.getFailureResponse(0, "数据为空");
        }
        String object = StringEscapeUtils.unescapeJava(financialInstitutionsDto);
        FinancialInstitutionsDto financing = JSON.parseObject(object, FinancialInstitutionsDto.class);
        FinancialInstitutions financialInstitutions = financialInstitutionsService.selectByKey(id);
        if ("0".equals(identifying)) {//0是保存
            int i = financialInstitutionsService.save(financing, proCode);
            if (i > 0) {
                return RspVo.getSuccessResponse(0, "保存成功");
            } else {
                return RspVo.getFailureResponse(0, "保存失败");
            }
        } else {
            /*注意 如果是修改审批状态 则是当前最新的融资报审的状态和主表的资料报审的审批状态一致*/
            //判断标书策划的状态
            if ("1".equals(financialInstitutions.getProcessStatus()) || "9".equals(financialInstitutions.getProcessStatus())) {
                return RspVo.getFailureResponse(0, "审批中或审批已完成，修改失败");
            }
            if (StringUtils.isNotBlank(financialInstitutions.getOaId())) {
                oaFlowService.finishOA(financialInstitutions.getOaId());
            }
            //提交流程  先保存
            int i = financialInstitutionsService.save(financing, proCode);
            if (i > 0) {//保存成的情况 走流程
                //登录人员信息
                AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
                //发起流程
                String process = capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE8, object, id, proCode, vo);
                if (!StringUtils.isEmpty(process)) {
                    if ("1".equals(financialInstitutions.getGuaranteeStatus()))
                    {//选择发待办
                        String oaTitle = UtilTools.getCapOaTitle(financialInstitutions.getProName(), CapProcessDetailTypeEnum.PRO_NODE_TYPE10 );
                        String oaId = oaFlowService.sendOAToDo(oaTitle, vo.getId(), financialInstitutions.getAddBy(), FlowTemplateEnum.MKT_SETUP_PRO.getSrcBizTable(), financialInstitutions.getId());
                        if (StringUtils.isNotBlank(oaId)) {
                            FinancialInstitutions institutions = new FinancialInstitutions();
                            institutions.setId(financialInstitutions.getId());
                            institutions.setOaId(oaId);
                            institutions.setUptBy(vo.getId());
                            institutions.setUptTime(new Date());
                            financialInstitutionsDao.updateById(institutions);
                        }
                    }

                    return RspVo.getSuccessResponse(0, "提交成功");
                }
                return RspVo.getFailureResponse(0, "提交失败");
            } else { //提交-保存失败
                return RspVo.getFailureResponse(0, "提交失败");
            }


        }
    }


}
